package xyz.ibenben.zhongdian.system.service.sys.impl;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;
import xyz.ibenben.zhongdian.common.annotation.SystemServiceLog;
import xyz.ibenben.zhongdian.common.constants.Constants;
import xyz.ibenben.zhongdian.common.shiro.PasswordHelper;
import xyz.ibenben.zhongdian.system.dao.sys.SysUserDao;
import xyz.ibenben.zhongdian.system.entity.sys.SysUser;
import xyz.ibenben.zhongdian.system.form.sys.SysUserForm;
import xyz.ibenben.zhongdian.system.mapper.sys.SysUserMapper;
import xyz.ibenben.zhongdian.system.service.impl.AbstractServiceImpl;
import xyz.ibenben.zhongdian.system.service.sys.SysUserRoleService;
import xyz.ibenben.zhongdian.system.service.sys.SysUserService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

/**
 * 系统用户服务实现类
 * 系统级用户所使用的，是权限系统中的一部分
 * 提供了一些基本的服务，如根据用户名称查询用户信息列表、根据站内信类型获取用户等方法。
 *
 * @author chenjian
 * @since 2017年9月27日上午10:57:28
 */
@Service("sysUserService")
public class SysUserServiceImpl extends AbstractServiceImpl<SysUser> implements SysUserService {
    @Resource
    private SysUserDao sysUserDao;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysUserMapper sysUserMapper;

    /**
     * selectByUsername用户记录
     *
     * @param username 参数
     * @return 返回值
     */
    @Override
    @SystemServiceLog(description = "selectByUsername用户记录")
    public SysUser selectByUsername(String username) {
        List<SysUser> userList = sysUserDao.selectByExample(getExample(null, username, null));
        if (!userList.isEmpty()) {
            return userList.get(0);
        }
        return null;
    }

    /**
     * save用户记录
     *
     * @param entity  参数
     * @param request 参数
     * @return 返回值
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    @SystemServiceLog(description = "save用户记录")
    public int save(SysUser entity, HttpServletRequest request) {
        PasswordHelper passwordHelper = new PasswordHelper();
        passwordHelper.encryptPassword(entity);
        //此时没有用户主键需要保存后拿到此主键再更新记录的时间和操作人
        int result = sysUserDao.insert(entity);
        if (result != 0) {
            entity.setCreateId(entity.getId());
            entity.setCreateTime(new Date());
            entity.setUpdateId(entity.getId());
            entity.setUpdateTime(new Date());
            result = sysUserDao.updateByPrimaryKey(entity);
        }
        return result;
    }

    /**
     * delete用户记录
     *
     * @param key     参数
     * @param request 参数
     * @return 返回值
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = {Exception.class})
    @SystemServiceLog(description = "delete用户记录")
    public int delete(Object key, HttpServletRequest request) {
        int result = 0;
        //删除用户角色表
        int resultUR = sysUserRoleService.deleteByUserId(key);

        //删除用户表
        SysUser entity = this.selectByKey(key);
        entity.setDelFlag(1);
        entity.setDelId((Long) request.getSession().getAttribute(Constants.SESSIONID));
        entity.setDelTime(new Date());
        int resultU = sysUserDao.updateByPrimaryKey(entity);
        //关系表为物理删除，用户表为逻辑删除
        //当都不为0时才能返回用户返回的数字
        if (resultUR != 0 && resultU != 0) {
            result = resultU;
        }
        return result;
    }

    /**
     * findByType用户记录
     *
     * @param ordinal 参数
     * @return 返回值
     */
    @Override
    @SystemServiceLog(description = "findByType用户记录")
    public List<SysUser> findByType(int ordinal) {
        return sysUserDao.selectByExample(getExample(null, null, ordinal));
    }

    /**
     * checkExsit用户记录
     *
     * @param email    参数
     * @param username 参数
     * @return 返回值
     */
    @Override
    @SystemServiceLog(description = "checkExist用户记录")
    public SysUser checkExist(String email, String username) {
        List<SysUser> list = sysUserDao.selectByExample(getExample(email, username, null));
        if (list != null && !list.isEmpty()) {
            return list.get(0);
        }
        return null;
    }

    /**
     * 根据各种条件去查询
     *
     * @param email    邮箱
     * @param username 用户名称
     * @param ordinal  类型
     * @return 条件实例
     */
    private Example getExample(String email, String username, Integer ordinal) {
        Example example = new Example(SysUser.class);
        Example.Criteria criteria = example.createCriteria();
        if (StringUtils.isNotBlank(email)) {
            criteria.andEqualTo("email", email);
        }
        if (StringUtils.isNotBlank(username)) {
            criteria.andEqualTo("username", username);
        }
        if (null != ordinal) {
            criteria.andEqualTo("type", ordinal);
        }
        return example;
    }

    /**
     * 更新记录
     *
     * @param user 用户实体
     */
    @Override
    public void updateWithoutRequest(SysUser user) {
        sysUserDao.updateByPrimaryKeySelective(user);
    }

    @Override
    public List<SysUser> findAll(SysUserForm sysUserForm) {
        return sysUserMapper.findAll(sysUserForm);
    }

    @Override
    public SysUser findByKey(Long id) {
        return sysUserMapper.findByKey(id);
    }

    @Override
    public SysUser selectUserWithRoleByUsername(String username) {
        return sysUserMapper.selectUserWithRoleByUsername(username);
    }
}
